<template>
  <div class='login_container'>
    <van-nav-bar title="极客头条-登录" />
    <van-form @submit="onSubmit">
      <van-field v-model="user.mobile" name="mobile" label="手机号" required placeholder="请输入11位手机号"
        :rules="[{ required: true, pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号', trigger: 'onChange' }]" />
      <van-field v-model="user.code" type="password" name="code" required label="验证码" placeholder="请输入6位验证码"
        :rules="[{ required: true, pattern: /^\d{6}$/, message: '请填写正确的验证码',trigger: 'onChange' }]" />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit" :disabled="isLoading" :loading="isLoading" loading-text="正在登录中...">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { Notify, Toast } from 'vant'
import { setToken } from '@/utils/token'

export default {
  name: 'MyLogin',
  data () {
    return {
      user: {
        mobile: '13888888888',
        code: '246810'
      },
      isLoading: false
    }
  },
  components: {},
  methods: {
    // 1.点击登录
    async onSubmit () {
      try {
        this.isLoading = true
        const { data: res } = await loginAPI(this.user)
        if (res.message === 'OK') {
          Toast.success('登录成功')
          // 将token存入本地
          setToken(res.data.token)
          sessionStorage.setItem('refresh_token', res.data.refresh_token)
          // 跳转一定要写到最后,replace模式，不需要回退
          this.$router.replace({
            path: this.$route.query.path || '/layout/home'
          })
        }
      } catch (err) {
        Notify({ type: 'danger', message: '账号或密码错误' })
      }
      this.isLoading = false
    }
  },
  created () { },
  mounted () { }
}
</script>

<style lang='less' scoped>
.van-form {
  margin-top: 16px;
}
</style>
